package com.soloyogame.anitoys.center.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.soloyogame.anitoys.util.constants.ManageContainer;


/**
 * 用户登录过滤器
 * @author shaojian
 */
public class LoginFilter implements Filter 
{
	private static final String LOGIN_URL = "/manage/user/login";
	
	public void init(FilterConfig arg0) throws ServletException 
	{
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		if(true)
		{
			chain.doFilter(request, response);
			return ;
		}
		 HttpServletRequest req = (HttpServletRequest) request;
		 HttpServletResponse res = (HttpServletResponse) response;
		 HttpSession session = req.getSession(true);  
	     // 从session 里面获取用户名的信息  
	     Object obj = session.getAttribute(ManageContainer.manage_session_business_info);
	     // 判断如果没有取到用户信息，就跳转到登陆页面，提示用户进行登陆  
	     if (obj == null || "".equals(obj.toString())) {  
	    	 res.sendRedirect(LOGIN_URL);  
	     }  
		chain.doFilter(request, response);
	}

	
	/** 获取IP */
	private String getIp(HttpServletRequest request) 
	{
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
		{
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
		{
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) 
		{
			ip = request.getRemoteAddr();
		}

		return ip;
	}
    
	// 可以通过的URL集合
	static Map<String, String> canMap = new HashMap<String, String>();

	// 当前应该选中的菜单
	static Map<String, String> menuMap = new HashMap<String, String>();

	/**
	 * 能否通过
	 * @param servletPath
	 * @return true:可以通过;false:不能通过
	 */
	private boolean canPass(String servletPath) 
	{
		for (Iterator<Entry<String, String>> it = canMap.entrySet().iterator(); it
				.hasNext();) 
		{
			Entry<String, String> entry = it.next();
			if (servletPath.indexOf(entry.getValue()) != -1)
			{
				return true;
			}
		}
		return false;
	}

	public void destroy() 
	{

	}
}
